<template>
  <div class="app-container">
    <a-title @clickPreview="preview" />
    <el-row :gutter="20" v-loading="importLoading" element-loading-text="导入中">
      <!-- tree v-loading="treeLoading" -->
      <el-col :span="6" :xs="24" 
      :element-loading-text="loadingText" v-loading="treeLoading">
        <el-row style="margin-bottom:10px;">
          <el-col>
            <el-dropdown trigger="click" @command="handleCommand">
              <el-button type="primary" size="mini" plain>
                导入模板
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="a">标准模板</el-dropdown-item>
                <el-dropdown-item command="b">
                  <el-upload
                    class="upload-demo"
                    ref="upload"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    action="#"
                  >自制模板</el-upload>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              type="primary"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
            >导出自制模板</el-button>
          </el-col>
        </el-row>
        <el-row> 
          <!--default-expand-all-->
          <el-col>
            <el-tree
              :data="treeData"
              node-key="guid"
              :expand-on-click-node="false"
              draggable
              :allow-drag="allowDrag"
              :allow-drop="allowDrop"
              @node-drag-end="handleDrop"
              @node-click="nodeClick"
              :default-expanded-keys="treeExpandData"
            >
              <span slot-scope="{ node, data }" class="custom-tree-node" style="width: 170px;">
                <span :title="node.label+'('+data.counts+')'" style="display:inline-block;width: 80%;overflow:hidden;font-size:11px;">{{ node.label }}({{data.counts}})</span>
                <!-- <span :title="node.label+'('+data.counts+')'">{{ node.label }}({{data.counts}})</span> -->
                <span class="childrenNum" v-if="(data.flag=='1')">
                  <el-dropdown trigger="click">
                    <i class="el-icon-more" />
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="editCatalog(node, data)">编辑</el-dropdown-item>
                      <el-dropdown-item @click.native="remove(node, data)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <i class="el-icon-plus" @click="() => addCatalog(node, data)" />
                </span>
              </span>
            </el-tree>
          </el-col>
        </el-row>
      </el-col>
      <!-- 项目文档 list -->
      <el-col :span="18" :xs="24">
        <el-form ref="queryParams" :model="queryParams" :inline="true" label-width="100px">
          <el-form-item label="文件标题" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入"
              clearable
              size="small"
              @input="change($event)"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="上传人" prop="publishPerson">
            <el-input
              v-model="queryParams.publishPerson"
              placeholder="请输入"
              clearable
              size="small"
              @input="change($event)"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="上传时间" prop="dateRange">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              size="small"
              value-format="yyyy-MM-dd"
              style="width:240px"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleUpload"
              :disabled="uplaoadReadonly"
            >文件上传</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-download"
              size="mini"
              :disabled="multiple"
              @click="bathDownload"
            >批量下载</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-folder-opened"
              size="mini"
              :disabled="multiple"
              @click="handleMove"
            >文件移动</el-button>
          </el-col>
        </el-row>

        <el-table
          stripe
          v-loading="loading"
          :data="dataList"
          @selection-change="handleSelectionChange"
          @sort-change="tableSortChange"
          :default-sort="{prop: 'createTime', order: 'descending'}"
        >
          <el-table-column type="selection" width="55" align="center" :selectable="checkSelect" />
          <el-table-column
            label="文件标题"
            align="left"
            prop="name"
            :sort-orders="['ascending', 'descending']"
            sortable="custom"
          />
          <el-table-column label="附件" align="left" prop="attachments" width="380">
            <template slot-scope="{row}">
              <div v-for="(item,index) in row.attachments" :key="index" class="fileTable">
                <el-tooltip
                  class="item"
                  effect="dark"
                  style="width:265px"
                  :content="item.fileName"
                  placement="top"
                >
                  <div class="fileTableTr">{{ item.fileName }}</div>
                </el-tooltip>

                <div v-if="item.fileName && row.type=='1'">
                  <a @click="downloadOne(item.fileId,item.fileName)" class="a-style">下载</a>
                  <!-- <a class="a-style" :href="item.storagePath" :download="item.fileName">下载</a> -->
                  <a class="a-style" @click="handlePreview(item)">预览</a>
                  <a v-show="item.archiveStatus == 0" class="a-style" @click="handleUpdateFile(item)">更新</a>
                </div>
                <div v-else-if="item.fileName && row.type=='0'">
                  <a @click="downloadOne(item.fileId,item.fileName)" class="a-style">下载</a>
                  <!-- <a class="a-style" :href="item.storagePath" :download="item.fileName">下载</a> -->
                  <a class="a-style" @click="handlePreview(item)">预览</a>
                </div>
                <div v-else-if="item.fileName && row.type=='2'">
                  <a @click="downloadOne(item.fileId,item.fileName)" class="a-style">下载</a>
                  <!-- <a class="a-style" :href="item.storagePath" :download="item.fileName">下载</a> -->
                  <a class="a-style" @click="handlePreview(item)">预览</a>
                </div>
                <div v-else-if="item.fileName && row.type=='3'">
                  <a @click="downloadOne(item.fileId,item.fileName)" class="a-style">下载</a>
                  <!-- <a class="a-style" :href="item.storagePath" :download="item.fileName">下载</a> -->
                  <a class="a-style" @click="handlePreview(item)">预览</a>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="上传人"
            align="center"
            prop="publishPerson"
            width="120"
            :sort-orders="['ascending', 'descending']"
            sortable="custom"
          />
          <el-table-column
            label="上传时间"
            align="center"
            prop="createTime"
            width="180"
            :sort-orders="['ascending', 'descending']"
            sortable="custom"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="80"
          >
            <template slot-scope="scope">
              <!-- <el-button
                size="mini"
                type="text"
                @click="handleDownload(scope.row)"
                icon="el-icon-download"
              >下载</el-button>-->
              <el-button
                v-show="!scope.row.status"
                v-if="scope.row.type==1"
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
                icon="el-icon-edit"
              >编辑</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 操作- 文件上传/修改 -->
    <el-dialog :visible.sync="isUpdate" width="800px" :show-close="false">
      <el-form ref="docForm" :model="docForm" :rules="docRules" label-width="80px">
        <el-form-item label="文件标题" prop="name">
          <el-input v-model="docForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="附件" prop="attachments">
          <vue-uploader
            v-if="isUpdate"
            :single-type="false"
            :file-list="docForm.attachments"
            @changeFileData="changeFile"
            @removeFileList="removeFileList"
            :pathName="pathName"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdate">确 定</el-button>
        <el-button @click="cancelUpdate">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 文件移动按钮 -->
    <el-dialog :visible.sync="isDirMove" width="400px" :show-close="false">
      <el-form label-width="80px">
        <el-tree
          :data="treefilterData"
          node-key="id"
          :expand-on-click-node="false"
          @node-click="handleNodeMove"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMove">确 定</el-button>
        <el-button @click="cancelMove">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 模板列表 -->
    <el-dialog :visible.sync="openTemplate" width="800px" :show-close="false">
      <el-form :model="formTemplateQuery" label-width="100px">
        <el-row>
          <el-col :span="18">
            <div class="grid-content bg-purple">
              <el-form-item label="模板名称" prop="name">
                <el-input v-model="formTemplateQuery.templateName" placeholder="请输入" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple-light">
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="handleQueryTemp"
                >查询</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <el-table v-loading="loading" :data="templateList">
        <el-table-column label="模版名称" align="center" prop="templateName" />
        <el-table-column label="业务类别" align="center" prop="businessCategoryName" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="templateImport(scope.row)"
              icon="el-icon-upload2"
              :disabled="isDisable"
            >导入</el-button>
            <el-button
              size="mini"
              type="text"
              @click="templatePreview(scope.row)"
              icon="el-icon-search"
            >在线预览</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="templateTotal>0"
        :total="templateTotal"
        :page.sync="formTemplateQuery.pageNum"
        :limit.sync="formTemplateQuery.pageSize"
        @pagination="getTemplateList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelTemplate">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 文档树-编辑操作 -->
    <el-dialog :visible.sync="isEditDoc" width="400px" :show-close="false">
      <el-form ref="dirForm" :model="dirForm" :rules="rules" label-width="80px">
        <el-form-item label="目录名称" prop="name">
          <el-input v-model="dirForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="dirForm.sort"
            placeholder="请输入"
            :precision="2"
            :step="0.1"
            style="width:100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editSubmit" :disabled="canClick">确 定</el-button>
        <el-button @click="cancelDoc">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="isUpdateFile" width="1000px" :show-close="false">
      <vue-uploader
        v-if="isUpdateFile"
        :single-type="true"
        :file-list="newAttachment"
        @changeFileData="updateChangeFile"
        @removeFileList="updateRemoveFileList"
        :pathName="pathName"
      />
      <el-row :gutter="10" class="mb8" style="margin:20px 0">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleDownloads"
          >批量下载</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="historyFileList" @selection-change="handleHistory">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="文件名称" align="left" prop="fileName" :show-overflow-tooltip="true" />
        <el-table-column label="上传用户" align="center" prop="createBy" />
        <el-table-column label="文件大小" align="center" prop="contentLength" />
        <el-table-column label="上传时间" align="center" prop="createTime">
          <template slot-scope="scope">{{ parseTime(scope.row.createTime,"{y}-{m}-{d} {h}:{i}") }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handlePreview(scope.row)"
              icon="el-icon-search"
            >预览</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="historyTotal>0"
        :total="historyTotal"
        :page.sync="historyParams.pageNum"
        :limit.sync="historyParams.pageSize"
        @pagination="getHistoryFiles"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateSumbit">确 定</el-button>
        <el-button @click="isUpdateFile=false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 预览 -->
    <el-dialog :visible.sync="openPreview" width="80%">
      <iframe :src="manualPreviewUrl" frameborder="0" width="100%" height="700px"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import { pickupList } from "@/api/business/pickup";
import { archiveListInDoc } from "@/api/business/dataArchive";
import { listDocCatalogTemplate } from "@/api/system/docCatalogTemplate";
import {
  treeselect,
  treeselectNew,
  treeselectFirstNew,
  addCatalog,
  updateCatalog,
  delCatalog,
  deleteCatalogCheck,
  exportCatalog,
  businessDocList,
  businessDoc,
  updateDoc,
  addDoc,
  deleteDoc,
  deleteCatalog,
  moveBusinessDoc,
  importData,
  importTemplate,
  historyFiles,
  updateFile,
  businessDocListResult,
  getCatalogCounts
} from "@/api/business/projectDoc";
import aTitle from "@/components/Title";
import vueUploader from "@/components/Uploader";
import { handleBatchDownload } from "@/api/zipdownload";
export default {
  name: "ProjectDoc",
  components: {
    aTitle,
    vueUploader
  },
  data () {
    return {
      props:{
        label: 'label',
        children: 'children',
        isLeaf: 'leaf'
      },
      manualPreviewUrl: null,
      openPreview: false,
      importLoading:false,
      pathName: "",
      isaddCatalog: false,
      isDisable: false,
      treeLoading:true,
      node_had:undefined,
      resolve_had:undefined,
      loadingText:"数据加载中",
      treeExpandData:[],
      treeData: [],
      treefilterData: [],
      addCatalogData:undefined,
      deleteCataloData:undefined,
      nickNames: [],
      // 遮罩层
      loading: false,
      // 选中数组
      guids: [],
      // 非单个禁用
      files: [],
      single: true,
      // 非多个禁用
      multiple: true,
      templateList: [],
      dateRange: [],
      // 总条数
      total: 0,
      // 项目文档列表 数据
      dataList: [],
      templateTotal: 0,
      formTemplateQuery: {
        pageNum: 1,
        pageSize: 10,
        templateName: undefined,
        businessCategoryId: undefined
      }, // 模板弹框form
      // 查询项目文档参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        createBy: undefined,
        businessId: undefined,
        catalogId: undefined
      },
      docRules: {
        name: [{ required: true, message: "文件标题不能为空", trigger: "blur" }]
      },
      rules: {
        name: [{ required: true, message: "目录名称不能为空", trigger: "blur" }]
      },
      fileList: [],
      docForm: {}, // 项目文档修改 form
      catalogId: null,
      dirForm: {
        name: null,
        sort: null,
        guid: null
      }, // 项目文档目录 修改 form
      dirFormMove: {}, // 项目文档目录移动 form
      docFormMove: {},
      openTemplate: false, // 模板弹框
      isUpload: false, // 文件上传弹框
      isDirMove: false, // 文件目录移动弹框
      isUpdate: false, // 更新弹框
      isEditDoc: false, // 文档编辑,
      isUpdateFile: false,
      historyFile: [],
      allHistoryFile: [],
      historyFileList: [],
      historyParams: {
        pageNum: 1,
        pageSize: 10,
        attachId: undefined
      },
      historyTotal: 0,
      newAttachmentId: null,
      newAttachment: [],
      uplaoadReadonly: true,
      searchType: undefined,
      // uploading: true,
      filterText: "收资管理",
      canClick: false,
    };
  },
  created () {
    this.queryParams.businessId = this.$route.params.id;
    this.formTemplateQuery.businessCategoryId = this.$route.params.businessCategoryId;
    this.getList();
    this.getTemplateList();
    this.getTreeselect();
    this.pathName = `TJECdocuments/${this.$route.params.id}/项目文档`;
  },
  mounted(){
    document.title=document.getElementById("businessNameTitle").innerHTML;
  },
  methods: {
    preview () {
      this.openPreview = true;
      this.manualPreviewUrl = `${this.previewUrl}${encodeURIComponent(
        `${this.operationManual}业务主页/项目文档.xlsx`
      )}&name=${encodeURIComponent("项目文档.xlsx")}`;
    },
    getTreeselect () {
      this.treeLoading = true;
      this.loadingText = "数据加载中";
      var params = { businessId: this.$route.params.id };
      treeselect(params).then(response => {
        this.treeData = response.data;
        this.treeExpandData.push(this.treeData[0].guid);
        this.treeLoading = false;
      });
      treeselect(params).then(response => {
        if (response.data.length > 0) {
          if (response.data[0].children.length > 0) {
            response.data[0].children = response.data[0].children.filter(
              item => item.flag !== "0"
            );
          }
        }
        this.treefilterData = response.data;
      });
    },
    /** 查询项目文档列表 */
    getList () {
      this.loading = true;
      this.queryParams.type = this.searchType;
      businessDocList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.dataList.map(item =>{
            item.attachments.some(list=>{
              if(list.archiveStatus == '1' || list.archiveStatus == '2'){
                return item.status = true
              }
            })
          })
        });
    },
    nodeClick (node, data) {
      this.loading = true;
      this.searchType = node.flag;
      if(node.flag === "0"||node.flag === "2"){
        this.uplaoadReadonly = true;
      }else{
        this.uplaoadReadonly = false;
        this.queryParams.catalogId = node.guid;
      }
      if(node.flag === "3"){
        this.uplaoadReadonly = true;
      }
      this.queryParams.type = this.searchType
      businessDocList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
    },
    // 获取模板列表
    getTemplateList () {
      this.loading = true;
      listDocCatalogTemplate(this.formTemplateQuery).then(response => {
        this.templateList = response.rows;
        this.historyTotal = response.total;
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = [];
      this.resetForm("queryParams");
      this.handleQuery();
    },
    // 文档目录拖拽
    handleDrop (draggingNode, dropNode, dropType) {
      if(dropNode.data.flag == 3 || dropNode.data.flag == 2 || dropNode.data.flag == 0){
        this.msgInfo('禁止移动到该目录下');
        return;
      }
      // 父级不能移动到子级目录下
      let array = new Array();
      if(draggingNode.data.children){
        draggingNode.data.children.map(item=>{
          array.append(item.guid);
        })
      }
      if(array.indexOf(dropNode.data.guid)===0){
        this.msgInfo('禁止移动到该目录下');
        return;
      }
      this.dirFormMove = {};
      this.dirFormMove.parentId = dropNode.data.guid;
      this.dirFormMove.guid = draggingNode.data.guid;

      if (dropType == "before" && dropNode.level == 1) {
        this.dirFormMove.parentId = "0";
      }
      if(dropNode.data.guid == draggingNode.data.guid){
        return;
      }else{
        updateCatalog(this.dirFormMove).then(res => {
          if (res.code == 200) {
            this.msgSuccess("移动成功");
            //this.getTreeselect();
          }
        });
      }
    },
    // 模板列表搜索
    handleQueryTemp () {
      this.formTemplateQuery.pageNum = 1;
      this.getTemplateList();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.files = selection;
      this.guids = selection.map(item => item.guid);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      this.nickNames = selection.map(item => item.name)
    },
    // 表单重置
    reset () {
      this.form = {
        guid: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    downloadOne (id, name) {
      this.downloadBlob(id, name);
    },
    // 文件上传
    handleUpload () {
      if (this.docForm.catalogId) {
        this.catalogId = this.docForm.catalogId;
      } else {
        this.catalogId = this.queryParams.catalogId;
      }
      this.resetForm("docForm");
      this.docForm = {
        attachments: [],
        attachmentIds: []
      };
      this.isUpdate = true;
    },
    cancelUpload () {
      this.isUpload = false;
    },
    // 项目文档目录移动弹框确定
    submitMove () {
      this.docFormMove.guids = this.guids;
      if (!this.docFormMove.catalogId) {
        this.msgError("请选择目录");
      } else {
        moveBusinessDoc(this.docFormMove).then(res => {
          if (res.code == 200) {
            this.getTreeselect();
            this.getList();
            this.isDirMove = false;
            this.msgSuccess("移动成功");
          }
        });
      }
    },
    cancelMove () {
      this.isDirMove = false;
    },
    // 项目文档 修改
    handleUpdate (row) {
      this.guid = row.guid;
      //this.fileList = [];
      businessDoc(this.guid).then(res => {
        if (res.code === 200) {
          if (res.data && res.data.attachments) {
            res.data.attachmentIds = [];
            res.data.attachments.forEach(item => {
              res.data.attachmentIds.push(item.fileId);
            });
          }
          //this.fileList = res.data.attachmentIds;
          this.docForm = res.data;
          if (this.docForm.attachmentIds === null) {
            this.docForm.attachmentIds = [];
          }
        }
      });
      this.isUpdate = true;
    },
    // 修改&新增
    submitUpdate () {
      // if (this.uploading) {
      //   this.msgError("附件上传中");
      //   return false;
      // }
      this.docForm.catalogId = this.queryParams.catalogId;
      this.$refs["docForm"].validate(valid => {
        if (valid) {
          if (this.docForm.guid != undefined) {
            updateDoc(this.docForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.isUpdate = false;
                this.getList();
                this.getTreeselect();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            // this.docForm.attachmentIds = this.fileList;
            this.docForm.businessId = this.$route.params.id;
            addDoc(this.docForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.isUpdate = false;
                this.getList();
                this.getTreeselect();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    cancelUpdate () {
      this.isUpdate = false;
    },
    // 附件操作
    changeFile (id, name) {
      // this.fileList.push(id);
      //this.docForm.attachmentIds = this.fileList
      this.docForm.attachmentIds.push(id);
      // this.uploading = false;
      // this.$set(this.docForm.attachments, this.docForm.attachments.length, { fileName: name, fileId: id })
    },
    removeFileList (id) {
      this.docForm.attachmentIds = this.docForm.attachmentIds.filter(
        item => item != id
      );
      this.docForm.attachments = this.docForm.attachments.filter(
        item => item.fileId != id
      );
    },
    getHistoryFiles () {
      this.loading = true;
      historyFiles(this.historyParams).then(res => {
        if (res.code === 200) {
          this.historyFileList = res.rows;
          this.historyTotal = res.total;
          res.rows.map(item => {
            this.allHistoryFile.push({
              guid: item.guid,
              fileName: item.fileName
            });
          });
          this.allHistoryFile = res.rows;
          this.loading = false;
        }
      });
    },
    handleUpdateFile (row) {
      this.isUpdateFile = true;
      this.historyParams.attachId = row.fileId;
      this.newAttachment = [
        {
          fileName: row.fileName,
          fileId: row.fileId,
          storagePath: row.storagePath
        }
      ];
      this.getHistoryFiles();
    },
    handleHistory (selection) {
      this.historyFile = selection;
    },
    updateSumbit () {
      updateFile(this.historyParams.attachId, this.newAttachmentId).then(
        res => {
          if (res.code === 200) {
            this.msgSuccess(res.msg);
            this.isUpdateFile = false;
          }
        }
      );
    },
    // handleDownload (row) {
    //   const filesList = [];
    //   filesList.push({
    //     fileurl: "/api/system/download/" + row.guid,
    //     fileName: row.attachments.fileName
    //   });
    //   handleBatchDownload(filesList);
    // },
    handleDownloads () {
      const filesList = [];
      if (this.historyFile.length === 0) {
        this.allHistoryFile.map(item => {
          filesList.push({
            fileurl: "/api/system/download/" + item.guid,
            fileName: item.fileName
          });
        });
        handleBatchDownload(filesList);
      } else {
        this.historyFile.map(item => {
          filesList.push({
            fileurl: "/api/system/download/" + item.guid,
            fileName: item.fileName
          });
        });
        handleBatchDownload(filesList);
      }
    },
    // 预览
    handlePreview (row) {
      this.filePreview(row.fileName, row.storagePath);
    },
    bathDownload () {
      const filesList = []
      this.files.map(item => {
        if (item.attachments.length > 0) {
          item.attachments.map(obj => {
            filesList.push({
              fileurl: "/api/system/download/" + obj.fileId,
              fileName: obj.fileName
            });
          });
        } else {
          this.msgError(item.name + "文件中没有附件");
        }
      });
      handleBatchDownload(filesList);
    },
    /** 导出按钮操作 */
    handleExport () {
      const queryParams = this.queryParams;
      this.$confirm(
        "为避免导入时出错，自制模板仅供导入时使用，请勿修改！",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function () {
          return exportCatalog(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function () { });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const guids = row.guid || this.guids;
      const nickNames = row.name || this.nickNames;
      this.$confirm(
        '是否确认删除文件标题为"' + nickNames + '"的文件及其附件?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function () {
          return deleteDoc(guids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () { });
    },
    // 文件目录移动弹框单机事件
    handleNodeMove (data, node) {
      this.docFormMove.catalogId = data.guid;
    },
    /** 导入按钮操作 */
    handleImport () {
      this.openTemplate = true;
    },
    // 取消按钮
    cancelTemplate () {
      this.openTemplate = false;
    },
    // 在线预览
    templatePreview (row) {
      this.filePreview(
        row.attachmentList[0].fileName,
        row.attachmentList[0].storagePath
      );
    },
    templateImport (row) {
      var $this = this;
      getCatalogCounts(this.$route.params.id).then(res=>{
        if(res.code==200 && res.data>0){
          $this.$message({
            message: "已有目录存在，请清空目录后再导入标准模版!",
            type: "warning"
          });
        }else{
          $this.getImportTem(row.guid);
        }
      });
    },
    getImportTem (guid) {
      this.openTemplate = false;
      this.isDisable = true;
      this.importLoading = true;
      importTemplate(guid, this.$route.params.id).then(res => {
        if (res.code === 200) {
          this.importLoading = false;
          this.msgSuccess(res.msg);
          this.getTreeselect();
          this.isDisable = false;
          this.node_had.childNodes = [];//把存起来的node的子节点清空，不然会界面会出现重复树！
          this.loadTreeNodes(this.node_had, this.resolve_had);//再次执行懒加载的方法
        }else{
          this.importLoading = false;
        }
        
      });
    },
    // 导入清单
    handleCommand (command) {
      if (command === "a") {
        this.openTemplate = true;
      }
    },
    beforeUpload (file) {
      let formData = new FormData();
      formData.append("file", file);
      formData.append("businessId", this.$route.params.id);
      if (
        file.name.split(".")[1] === "xlsx" ||
        file.name.split(".")[1] === "xls"
      ) {
        importData(formData).then(res => {
          this.getTreeselect();
        });
      } else {
        this.msgError("文件格式不正确");
      }
    },
    // 附件操作
    updateChangeFile (id, name) {
      this.newAttachmentId = id;
      this.newAttachment = [];
      // this.$set(this.docForm.attachments, this.docForm.attachments.length, { fileName: name, fileId: id })
    },
    updateRemoveFileList (id) {
      this.newAttachment = this.newAttachment.filter(item => item.fileId != id);
    },
    // 目录管理操作
    remove (node, data) {
      const parent = node.parent;
      const children = parent.childNodes || parent.data;
      const index = children.findIndex(d => d.data.guid === data.guid);
      

      var $this =this;
      $this.treeLoading = true;
      this.loadingText = "删除中";
      if (node.level === 1) {
        $this.treeLoading = false;
        this.msgError("主目录不能被删除！");
      } else {

        deleteCatalogCheck(node.data.guid).then(res=>{
          if(res.data == -1){
            $this.treeLoading = false;
            this.msgError("目录下存在文档，不能被删除！");
          }else{
            $this.uplaoadReadonly = true;
            children.splice(index, 1);
            this.msgSuccess("删除成功");
            $this.treeLoading = false;
            $this.deleteCatalogTrue(node.data.guid);
          }
        });
      }
    },
    deleteCatalogTrue(guid){
      deleteCatalog(guid).then(res => {});
    },
    // 文件移动
    handleMove (row) {
      this.isDirMove = true;
    },
    /*
     *文档树-编辑
     */
    editCatalog (node, data) {
      this.editCatalogData = data;
      this.isaddCatalog = false;
      this.dirForm.guid = data.guid;
      this.dirForm.name = data.label;
      this.dirForm.sort = data.sort;
      this.dirForm.parentId = node.parent.data.guid;
      this.isEditDoc = true;
    },
    editSubmit () {
      if (this.isaddCatalog) {
        this.$refs["dirForm"].validate(valid => {
          if (valid) {
            var addCatalogData = this.addCatalogData;
            addCatalog(this.dirForm).then(res => {
              if (res.code == 200) {
                this.msgSuccess(res.msg);
                //this.getTreeselect();
                this.isEditDoc = false;
                if(!addCatalogData.children){
                  this.$set(addCatalogData, 'children', []);
                }
                addCatalogData.children.push({label:res.data.name,guid:res.data.guid,flag:'1',isEdit:'1',counts:0});
              }
            });
          }
        });
      } else {
        this.$refs["dirForm"].validate(valid => {
          if (valid) {
            var editCatalogData = this.editCatalogData;
            updateCatalog(this.dirForm).then(res => {
              if (res.code == 200) {
                editCatalogData.label = this.dirForm.name; 
                this.msgSuccess(res.msg);
                this.getTreeselect();
                this.isEditDoc = false;
              }
            });
          }
        });
      }
    },
    addCatalog (node, data) {
      this.addCatalogData = data;
      this.isaddCatalog = true;
      this.dirForm.guid = null;
      this.dirForm.name = null;
      this.dirForm.sort = null;
      this.dirForm.businessId = this.$route.params.id;
      this.dirForm.parentId = data.guid;
      this.isEditDoc = true;
      this.canClick = false;
    },
    cancelDoc () {
      this.isEditDoc = false;
    },
    checkSelect (row, index) {
      let isChecked = true;
      if (row.type === "1") {
        // 判断里面是否存在某个参数
        isChecked = true;
      } else {
        isChecked = false;
      }
      if(row.status){
        isChecked = false;
      }
      return isChecked;
    },
    allowDrag (node) {
      let flag = true;
      if (node.data.flag == "0" || node.data.flag == "2" ||node.data.flag == "3") {
        flag = false;
      }
      return flag;
    },
    allowDrop (draggingNode, dropNode, type) {
      let flag = true;
      if (type === "inner" && dropNode && (dropNode.data.flag == "0" || dropNode.data.flag == "2" || dropNode.data.flag == "3")) {
        flag = false;
      }
      if ((type === "prev" || type === "next") && dropNode.parent.level === 0) {
        flag = false;
      }
      return flag;
    },
    tableSortChange (column) {
      this.queryParams.pageNum = 1;

      if (column.order === "descending") {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "desc";
      } else {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "asc";
      }
      this.getList();
    },change(e) {
      this.$forceUpdate();
    },loadTreeNodes(node, resolve){
      if (node.level === 0) { // 第一次调用
      this.node_had = node;//这里是关键！在data里面定义一个变量，将node.level == 0的node存起来
        this.resolve_had = resolve;//同上，把node.level == 0的resolve也存起来
           var params = { businessId: this.$route.params.id,parentId:'0' };
            treeselectFirstNew(params).then(response => {
              this.treeLoading = false;
              this.queryParams.catalogId = response.data.guid;
              return resolve(response.data);
            });
      }
      if (node.level > 0){
        var params = { businessId: this.$route.params.id,parentId:node.data.guid };
        treeselectNew(params).then(response => {
          this.treeLoading = false;
          return resolve(response.data.sort(this.sortId));
        });
      } 
    },
    sortId(a,b){
       return a.sort-b.sort;  
    }
  }
};
</script>

<style lang="scss" scoped>
.tatletitle {
  margin: 0 20px;
}
.a-style {
  color: #409eff;
}

.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  .childrenNum {
    flex: 1;
    text-align: right;
  }
}
</style>
<style>
.el-tree-node.is-current > .el-tree-node__content {
    background-color: #a2baf4 !important;
    /*background-color: #617fc7 !important;
    background-color: #cde0fb !important;*/
    color: white;
  }
 
  .el-checkbox__input.is-checked+.el-checkbox__label {
    color: black;
}
</style>
